package cn.mandifal.seller.controller;

import cn.mandifal.pojo.DpSeller;
import cn.mandifal.seller.service.SellerService;
import com.alibaba.dubbo.config.annotation.Reference;
import entity.Result;
import entity.ResultCode;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;

/**
 * 商家 controller
 * @author ws
 */
@RestController
@RequestMapping("/sellerController")
public class SellerController {
    @Reference
    private SellerService sellerService;

    /**
     * 商户注册
     * @param seller 商家对象
     * @return 返回添加结果
     */
    @RequestMapping("/addSeller")
    public Result addSeller(@RequestBody DpSeller seller){
        //利用 spring security 的密码加密
        BCryptPasswordEncoder bCryptPasswordEncoder=new BCryptPasswordEncoder();
        String password = bCryptPasswordEncoder.encode(seller.getPassword());
        seller.setPassword(password);
        try {
            sellerService.addSeller(seller);
            return Result.success();
        } catch (Exception e) {
            e.printStackTrace();
            return Result.failed();
        }
    }

    /**
     * 更新商家资料
     * @param dpSeller 商家实体
     * @return 返回处理结果
     */
    @RequestMapping("/updateSellerInfo")
    public Result updateSellerInfo(@RequestBody DpSeller dpSeller){
        try {
            //更新修改时间
            dpSeller.setUpdateTime(new Date());
            sellerService.updateSellerInfo(dpSeller);
            return Result.success();
        } catch (Exception e) {
            e.printStackTrace();
            return Result.failed();
        }
    }

    /**
     * 回显商家信息
     * @return 返回商家实体
     */
    @RequestMapping("/findOneSeller")
    public DpSeller findOneSeller(){
        String sellerId = SecurityContextHolder.getContext().getAuthentication().getName();
        return sellerService.findOneSeller(sellerId);
    }
}
